package com.sleepybit.wms.service;

import com.sleepybit.wms.entity.HomeInfo;
import com.sleepybit.wms.entity.Permit;
import com.sleepybit.wms.entity.Role;
import com.sleepybit.wms.entity.User;
import com.sleepybit.wms.mapper.PermitMapper;
import com.sleepybit.wms.mapper.RoleMapper;
import com.sleepybit.wms.mapper.SysMapper;
import com.sleepybit.wms.mapper.UserMapper;
import com.sleepybit.wms.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SysService {

    @Autowired
    private SysMapper sysMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermitMapper permitMapper;

    public HomeInfo getHomeInfo() {
        return sysMapper.getHomeInfo();
    }

    public User login(User user) throws Exception {
        user.setPassword(MD5Util.crypt(user.getPassword()));
        Integer check = sysMapper.checkUser(user);

        if (check > 0) {
            User user1 = sysMapper.getUser(user);
            List<Role> roleList = userMapper.getRoleByUser(user1);
            Map<String, Permit> map = new HashMap<String, Permit>();
            for (Role role : roleList) {
                List<Permit> permits = roleMapper.getPermitByRole(role);
                role.setPermitList(permits);
                permits.forEach(item -> {
                    map.put(item.getCode(), item);
                });
            }
            Collection<Permit> collection = map.values();
            List<Permit> permitList = new ArrayList<Permit>(collection);
            user1.setRoleList(roleList);
            user1.setPermitList(permitList);

            return user1;
        } else {
            return null;
        }
    }

    public List<Permit> getPermit() {
        return permitMapper.select(new Permit());
    }

    public Integer changePwd(User user) {
        return userMapper.update(user);
    }
}
